﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebStore.Domain.Entities.Model;

namespace WebStore.Web.App.Utility.Other
{
    public class Cart
    {

        public class ProductOrder
        {
            public Product Product { get; set; }
            public int Quantity { get; set; }
        }
        public Cart()
        {
            Orders = new List<ProductOrder>();
        }

        public IList<ProductOrder> Orders { get; set; }


        public void Add(Product product, int quantity)
        {
            var order = Orders.FirstOrDefault(x => x.Product.Id == product.Id);
            if (order == null)
                Orders.Add(new ProductOrder { Product = product, Quantity = quantity });
            else
                order.Quantity += quantity;
        }
        public void Remove(int productId, int quantity)
        {
            var order = Orders.FirstOrDefault(x => x.Product.Id == productId);
            order.Quantity = order.Quantity - quantity > 0 ? order.Quantity - quantity : 0;
            if (order.Quantity == 0)
                Orders.Remove(order);
        }
        public void RemoveAll(int productId)
        {
            var order = Orders.FirstOrDefault(x => x.Product.Id == productId);
            order.Quantity = 0;
        }
        public void Clear()
        {
            Orders.Clear();
        }

        public decimal TotalValue()
        {
            return Orders.Sum(x => x.Product.Price * x.Quantity);
        }
        public IEnumerable<KeyValuePair<int,int>> ToOrderDetails()
        {
            return Orders.Select(x => new KeyValuePair<int, int>(x.Product.Id, x.Quantity));
        }
    }
}